cmake_policy(PUSH)
cmake_policy(SET CMP0057 NEW)

include("${CMAKE_CURRENT_LIST_DIR}/../check-json.cmake")

function (check_build_database expect_basename fname component)
  if (component STREQUAL "NO_EXIST")
    if (EXISTS "${RunCMake_TEST_BINARY_DIR}/${fname}")
      list(APPEND RunCMake_TEST_FAILED
        "Build database detected before it is expected (${fname}).")
      set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}" PARENT_SCOPE)
    endif ()
    return ()
  endif ()

  if (NOT EXISTS "${RunCMake_TEST_BINARY_DIR}/${fname}")
    list(APPEND RunCMake_TEST_FAILED
      "No build database detected (${fname}).")
    set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}" PARENT_SCOPE)
    return ()
  endif ()

  if (component STREQUAL "ALL")
    set(CXXModules_config "Debug")
    set(suffix "all")
  elseif (component STREQUAL "ALL_MULTI")
    set(CXXModules_config "Debug")
    set(CXXModules_config_other "Release")
    set(suffix "all-multi")
  elseif (component STREQUAL "JUST_CXX")
    set(CXXModules_config "Debug")
    set(suffix "cxx")
  elseif (component STREQUAL "JUST_CXX_MULTI")
    set(CXXModules_config "Debug")
    set(CXXModules_config_other "Release")
    set(suffix "cxx-multi")
  elseif (component STREQUAL "CXX_AND_DEBUG")
    set(CXXModules_config "Debug")
    set(suffix "cxx-config")
  elseif (component STREQUAL "CXX_AND_RELEASE")
    set(CXXModules_config "Release")
    set(suffix "cxx-config")
  elseif (component STREQUAL "JUST_DEBUG")
    set(CXXModules_config "Debug")
    set(suffix "config")
  elseif (component STREQUAL "JUST_RELEASE")
    set(CXXModules_config "Release")
    set(suffix "config")
  elseif (component STREQUAL "JUST_TARGET_DEBUG")
    set(CXXModules_config "Debug")
    set(suffix "target")
  elseif (component STREQUAL "JUST_TARGET_RELEASE")
    set(CXXModules_config "Release")
    set(suffix "target")
  elseif (component STREQUAL "JUST_TARGET")
    set(CXXModules_config "Debug")
    set(suffix "target")
  else ()
    list(APPEND RunCMake_TEST_FAILED
      "Unrecognized test component for ${fname}: ${component}")
    set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}" PARENT_SCOPE)
    return ()
  endif ()

  set(expected_file "${CMAKE_CURRENT_FUNCTION_LIST_DIR}/expect/${expect_basename}-${suffix}.json")
  if (NOT EXISTS "${expected_file}")
    list(APPEND RunCMake_TEST_FAILED
      "No expected output JSON file found: ${expected_file}")
    set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}" PARENT_SCOPE)
    return ()
  endif ()

  file(READ "${RunCMake_TEST_BINARY_DIR}/${fname}" actual)
  file(READ "${expected_file}" expect)

  check_json("${actual}" "${expect}")

  set(RunCMake_TEST_FAILED "${RunCMake_TEST_FAILED}" PARENT_SCOPE)
endfunction ()

cmake_policy(POP)
